import { useAppSelector } from '@/redux/store';
import { useRef } from 'react';
import type { orgRequestParams, posRequestParams, roleRequestParams, YmChoiceStaffModalProps } from 'ym-design';
import { getOrgList, getPositionByGroup, getRoleByGroup } from './data';

type ChoiceType = 'org' | 'role' | 'pos';

type ChoiceStaffOptions = {
  onlyPerson: boolean;
  multiple: boolean;
  choiceType: Array<ChoiceType>;
};

type ChoiceStaffRef = {
  close: () => void;
  open: () => void;
};

export function useChoiceStaff(options?: Partial<ChoiceStaffOptions>): YmChoiceStaffModalProps & {
  ref: React.RefObject<ChoiceStaffRef>;
} {
  const ref = useRef<ChoiceStaffRef>(null);
  const entInfo = useAppSelector((state) => state.loginEnt);

  const orgRequest: YmChoiceStaffModalProps['orgRequest'] = async (params: orgRequestParams) => {
    const orgResult: any = await getOrgList(params);

    return orgResult;
  };

  const roleRequest: YmChoiceStaffModalProps['roleRequest'] = async (params: roleRequestParams) => {
    const roleResult: any = await getRoleByGroup(params);
    return roleResult;
  };

  const posRequest: YmChoiceStaffModalProps['posRequest'] = async (params: posRequestParams) => {
    const posResult: any = await getPositionByGroup(params);
    return posResult;
  };

  const allRequest = {
    orgRequest,
    roleRequest,
    posRequest,
  };

  const realRequest = options?.choiceType?.length
    ? Object.keys(allRequest).reduce((acc, cur) => {
        const isExist = options.choiceType?.some((key) => cur.includes(key));
        isExist && Reflect.set(acc, cur, allRequest[cur as keyof typeof allRequest]);
        return acc;
      }, {})
    : allRequest;

  return {
    ref,
    requestParams: { entId: entInfo.entId, entName: entInfo.entName! },
    onlyChoicePeople: options?.onlyPerson,
    choiceBtn: options?.multiple ? 'checkbox' : 'radio',
    ...realRequest,
  };
}
